home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14721 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: colossus.holonet.net!russell
  2. From: russell@news.mdli.com (Russell Blackadar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Proper use of friend keyword
  5. Date: 1 Apr 1996 20:17:04 GMT
  6. Organization: HoloNet National Internet Access System: 510-704-1058/modem
  7. Message-ID: <4jpdk0$sds@colossus.holonet.net>
  8. References: <4jn3qk$3tl6@holly.ACNS.ColoState.EDU>
  9. NNTP-Posting-Host: jubal.mdli.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Corby S. Hudnall (corbyh@holly.ACNS.ColoState.EDU) wrote:
  13. > Hey all, I have a question about how to use the friend keyword.  Consider
  14. > the following example:
  15. ...
  16. > class ABC
  17. > {
  18. >     int AValue;
  19. >     int GetAValue() { return (AValue); }
  20. ...
  21. > };
  22. > class XYZ
  23. ...
  24. >     friend int ABC::GetAValue();
  25. > };
  26.  
  27. > void main()
  28.   ^^^^ NO, should be int main() !!
  29.  
  30. > {
  31. >   ABC abc;
  32. >   XYZ xyz;
  33. >   cout << xyz.GetAValue() << endl
  34.             ^^^ NO, see below
  35. ...
  36.  
  37. Friendship does not change a member's ownership -- so no matter
  38. what you do, you can't call GetAValue for an XYZ object.  Moreover,
  39. you can't just grab a class's private members (ABC::GetAValue) by
  40. declaring friendship -- ABC has to *grant* friendship.  In other
  41. words, if you want ABC::GetAValue to be callable from outside ABC,
  42. the friend declaration must be *inside* ABC.  The friend declaration
  43. names the function which is allowed to *call* GetAValue (as well as
  44. call other private members of ABC).
  45.  
  46. In the above, the function calling ABC::GetAValue is main, so to
  47. "make this work" you would need
  48.      friend int main();
  49. inside your ABC definition; and then you'd write
  50.      cout << abc.GetAValue() << endl;
  51. in main.  Of course, it would be frivolous and inadvisable to grant
  52. friendship to main; much more useful examples abound in C++ textbooks
  53. and I recommend you do some reading.
  54.  
  55. Good luck!  
  56. --
  57. Russell Blackadar,   russell@mdli.com
  58.